package com.knight.mall.admin.controller.register;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.knight.mall.admin.controller.BaseController;
import com.knight.mall.admin.web.utils.MallApiResponse;
import com.knight.mall.admin.web.utils.MallrApiResponseCode;
import com.knight.mall.dto.VerCodeDto;
import com.knight.mall.exception.ServiceException;
import com.knight.mall.model.Enterprise;
import com.knight.mall.query.EnterpriseQuery;
import com.knight.mall.service.CreateVerCodeService;
import com.knight.mall.service.EnterpriseService;
import com.knight.mall.utils.DigestsUtils;

@Controller
@RequestMapping("register")
public class RegisterController extends BaseController {

	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(RegisterController.class);

	@Autowired
	private EnterpriseService enterpriseService;

	@Resource(name = "createVerCodeService")
	private CreateVerCodeService createVerCodeService;

	/**
	 * 到注册页面
	 * 
	 * @return
	 */
	@RequestMapping(value = { "registerPage" }, method = RequestMethod.GET)
	public String registerPage() {

		return "userHome/register";
	}

	/**
	 * 校验账号是否存在
	 * 
	 * @param username
	 * @return
	 */
	@RequestMapping(value = { "checkUserName" }, method = RequestMethod.POST)
	@ResponseBody
	public MallApiResponse checkUserName(String username) {

		if (username != null && !"".equals(username.trim())) {
			EnterpriseQuery query = new EnterpriseQuery();
			query.setAccount(username);
			List<Enterprise> list = enterpriseService.queryList(query);
			if (list != null && list.size() > 0) {
				// 账号已经存在
				return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "账号已经存在!");
			}
		} else {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请输入账号!");
		}

		return MallApiResponse.create();
	}

	/**
	 * 注册方法
	 * 
	 * @param name
	 * @return
	 */
	@RequestMapping(value = { "register" }, method = RequestMethod.POST)
	@ResponseBody
	public MallApiResponse register(String account, String phone, String password, String verCode, String random,
			String passSign, HttpServletRequest request) {

		if (account == null || "".equals(account.trim())) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请输入账号!");
		}

		if (phone == null || "".equals(phone.trim())) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请输入手机号!");
		}

		if (password == null || "".equals(password.trim())) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请输入密码!");
		}

		if (verCode == null || "".equals(verCode.trim())) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请输入验证码!");
		}

		if (random == null || "".equals(random.trim())) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请求数据错误!");
		}

		if (passSign == null || "".equals(passSign.trim())) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请求数据错误!");
		}

		EnterpriseQuery query = new EnterpriseQuery();
		query.setAccount(account);
		List<Enterprise> list = enterpriseService.queryList(query);
		if (list != null && list.size() > 0) {
			// 账号已经存在
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "账号已经存在!");
		}

		String newPassSign = DigestsUtils.md5Hex(DigestsUtils.md5Hex((password + random).getBytes()).getBytes());

		if (!passSign.equals(newPassSign)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "非法请求!");
		}

		// 校验验证码是不是相等
		String cacheVerCode = createVerCodeService.getVerCode(phone);

		if (!verCode.equals(cacheVerCode)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "验证码不正确!");
		}

		logger.debug("key:{},获取的验证码是:{}", phone, cacheVerCode);

		Enterprise t = new Enterprise();
		t.setEnterpiseName(" ");
		t.setGmtCreate(new Date());
		t.setAccount(account.trim());
		t.setPassword(password.trim());
		t.setContactPhone(phone.trim());
		t.setDistributionMode(1);
		try {
			enterpriseService.add(t);
		} catch (ServiceException e) {
			logger.error("注册失败", e);
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "注册失败!");
		}

		return MallApiResponse.create();
	}

	/**
	 * 获取验证码
	 * 
	 * @param username
	 * @return
	 */
	@RequestMapping(value = { "getVerCode" }, method = RequestMethod.POST)
	@ResponseBody
	public MallApiResponse getVerCode(String phone, HttpServletRequest request) {

		if (phone == null || "".equals(phone)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "手机号为空!");
		}

		if (!isMobile(phone)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请输入正确的手机号!");
		}
		String newPhone = phone.trim();
		EnterpriseQuery query = new EnterpriseQuery();
		query.setContactPhone(newPhone);
		List<Enterprise> list = enterpriseService.queryList(query);

		if (list != null && list.size() > 0) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "手机号码已注册!");
		}

		// 获取验证码
		VerCodeDto dto = createVerCodeService.createVerCode(6, newPhone);

		if (dto == null) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "发送验证码错误!");
		}

		if (dto.getMessage() != null && !"".equals(dto.getMessage())) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), dto.getMessage());
		}

		logger.debug("key:{},生成的验证码是:{}", phone, dto.getVerCode());

		return MallApiResponse.create(dto.getVerCode());
	}

	/**
	 * 重置密码获取手机验证码
	 * 
	 * @param phone
	 * @param request
	 * @return
	 */
	@RequestMapping(value = { "getVerCodeForRestPass" }, method = RequestMethod.POST)
	@ResponseBody
	public MallApiResponse getVerCodeForRestPass(String phone, HttpServletRequest request) {
		if (phone == null || "".equals(phone)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "手机号为空!");
		}

		if (!isMobile(phone)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请输入正确的手机号!");
		}
		String newPhone = phone.trim();
		EnterpriseQuery query = new EnterpriseQuery();
		query.setContactPhone(newPhone);
		List<Enterprise> list = enterpriseService.queryList(query);

		if (list == null || list.size() <= 0) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "手机号码未注册!");
		}

		// 获取验证码
		VerCodeDto dto = createVerCodeService.createVerCode(6, newPhone);

		if (dto == null) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "发送验证码错误!");
		}

		if (dto.getMessage() != null && !"".equals(dto.getMessage())) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), dto.getMessage());
		}

		logger.debug("key:{},生成的验证码是:{}", phone, dto.getVerCode());

		return MallApiResponse.create(dto.getVerCode());
	}

	/**
	 * 找回密码页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "forgetPassword")
	public String forgetPassword() {

		return "userHome/getBackPassword";
	}

	/**
	 * 找回密码页面
	 * 
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping(value = "resetPassPage")
	public String resetPassPage(String phone, String code, Model model) throws ServiceException {

		if (phone == null || "".equals(phone)) {
			throw new ServiceException("手机号码为空");
		}

		if (code == null || "".equals(code)) {
			throw new ServiceException("验证码为空");
		}

		// 校验验证码是不是相等
		String cacheVerCode = createVerCodeService.getVerCode(phone);

		if (cacheVerCode == null) {
			// 手机号有误，或者验证码过期
			throw new ServiceException("请重新获取验证码");
		}

		if (!code.equals(cacheVerCode)) {
			// 验证码不正确
			throw new ServiceException("验证码错误");
		}

		model.addAttribute("phone", phone);
		model.addAttribute("code", code);
		return "userHome/resetPassword";
	}

	/**
	 * 找回密码提交方法
	 * 
	 * @return
	 */
	@RequestMapping(value = { "findPass" }, method = RequestMethod.POST)
	@ResponseBody
	public MallApiResponse findPass(String phone, String code, String pass1, String pass2, String random,
			String passSign) {

		if (phone == null || "".equals(phone)) {
			logger.error("method:{},message:{}", "findPass", "手机号码为空");
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请求数据错误!");
		}
		if (code == null || "".equals(code)) {
			logger.error("method:{},message:{}", "findPass", "验证码为空");
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请求数据错误,请重试!");
		}
		if (pass1 == null || "".equals(pass1)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请求数据错误,请重试!");
		}
		if (pass2 == null || "".equals(pass2)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请求数据错误,请重试!");
		}
		if (random == null || "".equals(random)) {
			logger.error("method:{},message:{}", "findPass", "随机码为空");
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请求数据错误,请重试!");
		}
		if (passSign == null || "".equals(passSign)) {
			logger.error("method:{},message:{}", "findPass", "签名为空");
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请求数据错误,请重试!");
		}
		if (!pass1.equals(pass2)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "新密码和确认密码不相同!");
		}
		String newPhone = phone.trim();
		// 校验验证码是不是相等
		String cacheVerCode = createVerCodeService.getVerCode(newPhone);
		if(cacheVerCode==null || "".equals(cacheVerCode)){
			logger.error("method:{},message:{}", "findPass", "验证码为空");
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请求数据错误,请重试!");
		}
		
		if (!code.equals(cacheVerCode)) {
			logger.error("method:{},message:{}", "findPass", "验证码不正确");
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请求数据错误,请重试!");
		}
		
		EnterpriseQuery query = new EnterpriseQuery();
		query.setContactPhone(newPhone);
		List<Enterprise> list = enterpriseService.queryList(query);
		
		if(list==null || list.size()!=1){
			logger.error("method:{},message:{}", "findPass", "手机号对应多条记录，数据错误");
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请求数据错误,请重试!");
		}
		
		//更新密码
		Enterprise e = list.get(0);
		Enterprise updateE = new Enterprise();
		updateE.setId(e.getId());
		updateE.setPassword(pass1);
		enterpriseService.update(updateE);
		
		return MallApiResponse.create();
	}

	/**
	 * 手机号验证
	 * 
	 * @param str
	 * @return 验证通过返回true
	 */
	public static boolean isMobile(String str) {
		Pattern p = null;
		Matcher m = null;
		boolean b = false;
		p = Pattern.compile("^[1][3,4,5,8][0-9]{9}$"); // 验证手机号
		m = p.matcher(str);
		b = m.matches();
		return b;
	}
	
	
	@RequestMapping(value = "/captcha", method = RequestMethod.GET)
    public void captcha(HttpServletRequest request, HttpServletResponse response,HttpSession session)
            throws ServletException, IOException 
    {
		 int width = 63;
	        int height = 37;
	        Random random = new Random();
	        //设置response头信息
	        //禁止缓存
	        response.setHeader("Pragma", "No-cache");
	        response.setHeader("Cache-Control", "no-cache");
	        response.setDateHeader("Expires", 0);

	        //生成缓冲区image类
	        BufferedImage image = new BufferedImage(width, height, 1);
	        //产生image类的Graphics用于绘制操作
	        Graphics g = image.getGraphics();
	        //Graphics类的样式
	        g.setColor(this.getRandColor(200, 250));
	        g.setFont(new Font("Times New Roman",0,28));
	        g.fillRect(0, 0, width, height);
	        //绘制干扰线
	        for(int i=0;i<40;i++){
	            g.setColor(this.getRandColor(130, 200));
	            int x = random.nextInt(width);
	            int y = random.nextInt(height);
	            int x1 = random.nextInt(12);
	            int y1 = random.nextInt(12);
	            g.drawLine(x, y, x + x1, y + y1);
	        }

	        //绘制字符
	        String strCode = "";
	        for(int i=0;i<4;i++){
	            String rand = String.valueOf(random.nextInt(10));
	            strCode = strCode + rand;
	            g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
	            g.drawString(rand, 13*i+6, 28);
	        }
	        //将字符保存到session中用于前端的验证
	        session.setAttribute("strCode", strCode);
	        g.dispose();

	        ImageIO.write(image, "JPEG", response.getOutputStream());
	        response.getOutputStream().flush();

    }
	
	private  Color getRandColor(int fc,int bc){
	        Random random = new Random();
	        if(fc>255)
	            fc = 255;
	        if(bc>255)
	            bc = 255;
	        int r = fc + random.nextInt(bc - fc);
	        int g = fc + random.nextInt(bc - fc);
	        int b = fc + random.nextInt(bc - fc);
	        return new Color(r,g,b);
	    }
}
